package com.cskaoyan.controller;

import com.cskaoyan.bean.MarketAdmin;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.data.AdminInfoBean;
import com.cskaoyan.bean.data.LoginUserData;
import com.cskaoyan.exception.InfoExpiredException;
import com.cskaoyan.exception.NoInfoException;
import com.cskaoyan.service.WxAuthSerrvice;
import com.cskaoyan.util.AuthenticationUtil;
import com.cskaoyan.util.WdTokenHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author QHC
 * @title WxAuthController
 * @date 2023/6/15 7:34
 * @description TODO
 */

@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    @Autowired
    WxAuthSerrvice wxAuthSerrvice;



    @RequestMapping("info")

    private BaseRespVo info(){

        MarketUser user = null;
        try {
            user = (MarketUser) AuthenticationUtil.getPrincipal();
        } catch (NoInfoException e) {
            return BaseRespVo.unAuthc();
        } catch (InfoExpiredException e) {
            return BaseRespVo.expired();
        }
        Map<String, Object> data = new HashMap<>();
        data.put("nikeName", user.getNickname());
        data.put("avatarUrl", user.getAvatar());
        return BaseRespVo.ok(data);

    }

    @RequestMapping("login")

    public BaseRespVo login(@RequestBody Map map){

        String username =(String) map.get("username");
        String password =(String) map.get("password");
        if (username==null||password==null){


            return  BaseRespVo.fail("用户名和密码不能够为空");
        }

        MarketUser user = wxAuthSerrvice.query(username, password);
        // 找不到当前用户
        if (user == null||user.getStatus() == 1) {
            return BaseRespVo.unAuthc();
        }
        // 能够找到当前用户
        String token = WdTokenHolder.genKey(user);
        // todo：更新log中的日志信息
        AdminInfoBean adminInfoBean = new AdminInfoBean(username, user.getAvatar());
        LoginUserData data = new LoginUserData(adminInfoBean, token);
        return BaseRespVo.ok(data);



       // return BaseRespVo.ok(user.getNickname());


    }
}
